// pages/grid/personnel/personnel.js
const app = getApp();
import util from '../../../utils/util'
import {
  AdminMember,
  GetAdminMemberList,
  GetTagsCategoryList,
  GetTagsList,
  UpMemeberTags,
  GetMemberHomeDetail,
  UpMemeberTagsNew
} from '../../../config/api'

Page({

  /**
   * 页面的初始数据
   */
  data: {
    isBottom: false, // 是否无数据触底了
    isReachBtm: false, // 是否触发上拉加载
    adminInfo: '',
    grider_master_info: [],

    vollege_id: 0,
    page: 1,
    limit: 10,
    name: '',
    adminMemberList: [],

    pindex: '', // 当前编辑下标
    edit_arr: [], // 编辑下标数组

    mindex: '', /// 成员编辑标识

    showView: true,
    showCat: true,
    tagsList: [],
    type: 1,
    formData: [],
    id: 0,
    homeType: 0,
    memberid: 0,
    tagsCatList: [],
    chekedtags: [],

    tagsName: [], // 当前选择的标签名称数组

    famliyTagsidArr: [], // 家庭标签参数数组
    memberTagsidArr: [], // 成员标签参数数组
    mid: '', // 成员id
    memberArr: [], // 成员数组
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    let adminInfo = wx.getStorageSync('adminInfo')
    let grider_storge = wx.getStorageSync('grider')

    console.log('grider_storge', grider_storge)
    let that = this;
    that.setData({
      adminInfo,
      grider_master_info: grider_storge,
      vollege_id: app.globalData.vollege_id
    })

    if (adminInfo) { // 判断管理员
      that.getAdminList()
    } else {
      that.getAdminMemberList();
    }
  },

  getAdminList() { // 管理员获取人员列表
    let that = this;
    wx.showLoading({
      title: '玩命加载中',
    })
    util.apiRequest(AdminMember, {
      vollege_id: app.globalData.vollege_id,
      name: that.data.name,
      page: that.data.page,
      limit: that.data.limit
    }, null).then(r => {
      console.log('管理员人员管理', r)
      var newList = that.data.adminMemberList.concat(r.data.data)
      if (r.data.data == '' && that.data.isReachBtm == true) {
        that.setData({
          isBottom: true
        })
        wx.showToast({
          title: '暂无更多',
          icon: 'none',
        })
      }
      that.setData({
        adminMemberList: newList
      })
      wx.hideLoading();
      if (newList.length == 0) {
        that.setData({
          isEmpty: true
        })
      } else {
        that.setData({
          isEmpty: false
        })
      }
    })
  },

  getAdminMemberList() { // 获取人员列表
    let that = this
    let grider_storge = wx.getStorageSync('grider')

    wx.showLoading({
      title: '玩命加载中',
    })

    util.apiRequest(GetAdminMemberList, {
      id: grider_storge.id,
      vollege_id: app.globalData.vollege_id,
      name: that.data.name,
      page: that.data.page,
      limit: that.data.limit
    }, null).then(r => {
      console.log('人员管理', r)
      var newList = that.data.adminMemberList.concat(r.data.data)
      if (r.data.data == '' && that.data.isReachBtm == true) {
        that.setData({
          isBottom: true
        })
        wx.showToast({
          title: '暂无更多',
          icon: 'none',
        })
      }
      that.setData({
        adminMemberList: newList
      })

      wx.hideLoading();

      if (newList.length == 0) {
        that.setData({
          isEmpty: true
        })
      } else {
        that.setData({
          isEmpty: false
        })
      }

    })
  },

  searchName(e) { // 搜索人
    console.log('esousuo:', e)
    console.log('姓名搜索：', e.detail.value)
    this.setData({
      page: 1,
      adminMemberList: [],
      name: e.detail.value,
      edit_arr:[],
      famliyTagsidArr:[],
      memberArr:[],
      memberTagsidArr:[],
    })

    if (this.data.adminInfo) {
      this.getAdminList() // 管理员村民列表
    } else {
      this.getAdminMemberList(); // 搜索时请求列表
    }
  },

  editChage: function(e) {
    console.log("编辑点击", e)
    let id = e.currentTarget.dataset.id
    let pindex = e.currentTarget.id; // 编辑标识
    let edit_arr = this.data.edit_arr;

    console.log('当前编辑下标：', pindex)

    edit_arr[pindex] = true;

    console.log('编辑标识下标家庭数组', edit_arr)

    this.setData({
      edit_arr,
      pindex
    })
  },

  closeCat: function() { // 关闭弹窗
    let that = this;
    that.setData({
      showCat: (!that.data.showCat)
    })
  },

  //调起标签选择框
  chageTage: function(e) {
    console.log("调起标签选择框")
    let edit_arr = this.data.edit_arr
    let pindex = e.currentTarget.id; // 家庭编辑标识
    console.log('家庭pindex', pindex)

    let mindex = e.currentTarget.dataset.m_index;
    console.log('成员下标：', mindex)

    let id = e.currentTarget.dataset.id
    let homeType = e.currentTarget.dataset.hometype
    let memberid = e.currentTarget.dataset.memberid

    console.log("homeType", homeType);

    if (homeType == 2) { // 成员时
      this.setData({
        mid: memberid
      })
    }

    this.setData({
      pindex,
      mindex,
    })

    if (edit_arr[pindex]) {
      this.setData({
        showCat: false,
        type: 1,
        homeType: homeType,
        id: id,
        memberid: memberid
      })
      this.getTagsCategoryList();
    }
  },

  //调取标签分类
  getTagsCategoryList() {
    let that = this
    util.apiRequest(GetTagsCategoryList, null, null).then(r => {
      console.log('标签分类', r)
      that.setData({
        tagsCatList: r.data.data,
      })
    })
  },

  //调取标签
  getTagsList(id) {
    let that = this
    util.apiRequest(GetTagsList, {
      cat_id: id
    }, null).then(r => {
      console.log('小标签', r)
      let tagsList = r.data.data
      util.apiRequest(GetMemberHomeDetail, {
        id: that.data.memberid,
        type: that.data.homeType
      }, null).then(r1 => {
        console.log('个详情', r1)
        let tags_arr = r1.data.data.tags_arr
        for (var i = 0; i < tagsList.length; i++) {
          for (var j = 0; j < tags_arr.length; j++) {
            console.log("tags_arr[j]", tags_arr[j])
            if (tagsList[i].id == tags_arr[j]) {
              tagsList[i]['checked'] = true;
              console.log(tagsList[i]['checked'])
            }
          }
        }
        that.setData({
          tagsList: tagsList
        })
        console.log("标签AA：", tagsList);
      })
    })
  },

  setmCat(e) { // 选择大标签
    let id = e.currentTarget.dataset.id
    let type = e.currentTarget.dataset.type
    let title = e.currentTarget.dataset.title
    let that = this;
    let fromData = that.data.formData
    if (type == 1) {
      that.getTagsList(id)
      that.setData({
        type: 2,
        showView: false,
        showCat: true,
      })
    }
  },

  checkboxChange(e) { // 多选标签
    console.log('多选', e)
    let tagsName = []
    const tagsList = this.data.tagsList
    const values = e.detail.value

    for (let i = 0, lenI = tagsList.length; i < lenI; ++i) {
      for (let j = 0, lenJ = values.length; j < lenJ; ++j) {
        if (tagsList[i].id == values[j]) {
          tagsName.push(tagsList[i].title)
          break;
        }
      }
    }

    console.log('多选的标签名称数组：', tagsName)

    this.setData({
      tagsName,
      chekedtags: values
    })
  },

  confirmLabel(e) { // 确定选择标签
    let pindex = e.currentTarget.id; // 编辑标识
    let mindex = this.data.mindex; // 成员下标

    console.log('确定当前编辑下标', pindex)
    console.log('确定选择的标签id：', this.data.chekedtags)
    console.log('确定选择的标签名称：', this.data.tagsName)

    console.log('this.data.mindex', this.data.mindex)
    console.log('确定时家庭成员id：', this.data.mid)

    if (this.data.mindex >= 0) {
      // 成员标签选择
      console.log('成员标签编辑tags_arr:', this.data.adminMemberList[pindex].memberList[this.data.mindex].tags_arr)
      this.data.adminMemberList[pindex].memberList[this.data.mindex]['tags_name'] = [];
      this.data.adminMemberList[pindex].memberList[this.data.mindex].tags_arr = this.data.chekedtags
      this.data.adminMemberList[pindex].memberList[this.data.mindex].tags_name = this.data.tagsName
      console.log('成员选择标签后列表：', this.data.adminMemberList)

      let memberObj = {};
      memberObj['type'] = 2
      memberObj['id'] = this.data.mid;
      memberObj['chekedtags'] = this.data.chekedtags
      let mArr = []
      mArr[mindex] = memberObj
      // mArr.push(memberObj)

      console.log('确定mArr：', mArr)
      console.log('77', !!this.data.memberArr[pindex])

      if (this.data.memberArr[pindex]) {
        console.log('第2后次成员选择')
        console.log('确定this.data.memberArr[pindex]', this.data.memberArr[pindex])

        this.data.memberArr[pindex].splice(mindex, 1, memberObj)
        console.log('删除替换后this.data.memberArr[pindex]', this.data.memberArr[pindex])
      } else {
        console.log('第一次成员选择')
        this.data.memberArr[pindex] = mArr
        console.log('3this.data.memberArr[pindex]', this.data.memberArr[pindex])
      }

      console.log('确定this.data.memberArr', this.data.memberArr)

      this.setData({
        memberArr: this.data.memberArr
      })

      this.data.memberTagsidArr[pindex] = this.data.memberArr[pindex] // 把成员数组赋值给成员参数数组

      console.log('确定时this.data.memberTagsidArr', this.data.memberTagsidArr)

    } else {
      // 家庭标签选择
      this.data.adminMemberList[pindex]['tags_name'] = []
      this.data.adminMemberList[pindex].tags_arr.push(...this.data.chekedtags)
      this.data.adminMemberList[pindex]['tags_name'].push(...this.data.tagsName)

      this.data.famliyTagsidArr[pindex] = this.data.chekedtags
      console.log('famliyTagsidArr：', this.data.famliyTagsidArr)

      console.log('668:', this.data.adminMemberList[pindex].tags_arr)
      console.log('b668:', this.data.adminMemberList[pindex].tags_name)
    }

    //console.log('确定选择标签后列表：',this.data.adminMemberList)
    this.setData({
      adminMemberList: this.data.adminMemberList,
      showView: true,
    })

  },

  onComplete(e) { // 完成提交
    let famliyTagsidArr = this.data.famliyTagsidArr;
    let memberTagsidArr = this.data.memberTagsidArr;

    console.log('完成时famliyTagsidArr', this.data.famliyTagsidArr)

    console.log('完成时memberTagsidArr:', this.data.memberTagsidArr)

    let pindex = e.currentTarget.id; // 家庭编辑标识
    let memberid = e.currentTarget.dataset.memberid // 家庭id
    let tagsidArr = this.data.famliyTagsidArr[pindex] // 家庭标签id数组

    console.log('家庭memberid:', memberid)
    console.log('家庭tagsidArr:', tagsidArr)
    console.log('家庭编辑index:', pindex)

    let edit_arr = this.data.edit_arr
    edit_arr[pindex] = false

    this.setData({
      edit_arr
    })

    console.log('点击完成后edit_arr：', edit_arr)

    if (famliyTagsidArr.length != 0) { // 家庭标签提交
      console.log('家庭提交')
      let params = {
        id: memberid,
        type: 1,
        chekedtags: tagsidArr
      }
      this.sendData(params, pindex)
    }

    if (memberTagsidArr.length != 0) { // 成员标签提交
      console.log('进入成员提交')
      console.log('某个家庭成员提交参数数组：', memberTagsidArr[pindex])
      let that = this;
      let memberParamsArr = memberTagsidArr[pindex]
      memberParamsArr.forEach(function(item, index) {
        console.log('某个成员参数', item)
        that.sendData(item, pindex)
      })
    }

  },

  sendData(params, pindex) { // 数据传输到服务器
    let that = this
    console.log("表单参数", params)
    console.log('完成时famliyTagsidArr', this.data.famliyTagsidArr)
    console.log('请求完成时memberTagsidArr:', this.data.memberTagsidArr)

    let famliyTagsidArr = this.data.famliyTagsidArr
    let memberTagsidArr = this.data.memberTagsidArr
    let memberArr = this.data.memberArr

    util.apiRequest(UpMemeberTagsNew, params).then(r => {
      console.log('表单提交', r)
      if (r.data.code == 1) {
        // 清空成员提交后的参数
        famliyTagsidArr.splice(pindex, 1)
        memberTagsidArr.splice(pindex, 1)
        memberArr.splice(pindex, 1)

        console.log('清空后famliyTagsidArr', famliyTagsidArr)
        console.log('清空后memberTagsidArr', memberTagsidArr)
        console.log('清空后memberArr', memberArr)
        that.setData({
          memberTagsidArr,
          memberArr
        })
      }
      wx.showToast({
        title: r.data.info,
        icon: 'none'
      })
    })
  },

  //表单提交
  sumbitFrom() {
    let that = this

    let parm = {
      id: that.data.memberid,
      type: that.data.homeType,
      chekedtags: that.data.chekedtags
    }
    console.log("表单参数", parm)
    util.apiRequest(UpMemeberTagsNew, parm).then(r => {
      console.log('表单提交', r)
      wx.showToast({
        title: r.data.info,
        icon: 'success',
        duration: 2000
      })
      that.setData({
        page: 1,
        adminMemberList: [],
        chekedtags: [],
        showView: true,
      })

      console.log('是否是管理员：', that.data.adminInfo)

      if (that.data.adminInfo) {
        that.getAdminList() // 管理员村民列表
      } else {
        that.getAdminMemberList(); // 搜索时请求列表
      }

    })
  },

  qx() {
    this.setData({
      chekedtags: [],
      showView: true,
    })
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {
    var that = this;
    var page = this.data.page;

    that.setData({
      isReachBtm: true
    })

    if (that.data.isBottom) return;

    page++;
    that.setData({
      page: page
    })

    console.log('page++', page)
    if (that.data.adminInfo) {
      that.getAdminList() // 管理员村民列表
    } else {
      that.getAdminMemberList(); // 搜索时请求列表
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})